package org.mbm.io.thread;

import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;


public class View extends JFrame {
    JPanel container;
    String lastVisited = lastVisited();

    public View() {
        setTitle("Viewer");
        setSize(600, 500);
        setLocation(200, 100);
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        container = new JPanel();
        container.setLayout(new BorderLayout());
        // container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
        container.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));

        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                LogReader.markClose();
                System.exit(0);
            }
        });
    }

    private void init() {
        JPanel pnlTop = new JPanel();
        pnlTop.setLayout(new BoxLayout(pnlTop, BoxLayout.X_AXIS));
        pnlTop.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

        // simple text field.
        final JTextField path = new JTextField(2);
        path.setText(lastVisited);
        pnlTop.add(path);

        final JFileChooser fileChooser = new JFileChooser();
        if (lastVisited != null)
            fileChooser.setCurrentDirectory(new File(lastVisited));
        fileChooser.setFileFilter(new FileFilter() {

            @Override
            public String getDescription() {
                return "Log files";
            }

            @Override
            public boolean accept(File f) {
                if (f.isDirectory())
                    return true;
                String name = f.getName().toLowerCase();
                if (name.endsWith(".log") || name.endsWith(".txt"))
                    return true;

                return false;
            }
        });
        JButton browse = new JButton("Browse");

        pnlTop.add(browse);
        browse.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int result = fileChooser.showOpenDialog(container);
                if (JFileChooser.APPROVE_OPTION == result) {
                    File selFile = fileChooser.getSelectedFile();
                    if (selFile != null) {
                        String p = selFile.getAbsolutePath();
                        path.setText(p);
                        saveVisited(p);
                    }

                }

            }
        });
        pnlTop.add(Box.createRigidArea(new Dimension(5, 0)));

        // a button.
        JButton load = new JButton("Load");
        pnlTop.add(load);

        container.add(pnlTop, BorderLayout.NORTH);

        // text area
        final JTextArea textArea = new JTextArea();
        textArea.setDisabledTextColor(Color.GRAY);
        textArea.setEditable(false);

        // scroll pane attached to text area
        JScrollPane scrollPane = new JScrollPane(textArea, VERTICAL_SCROLLBAR_ALWAYS, HORIZONTAL_SCROLLBAR_AS_NEEDED);
        container.add(scrollPane, BorderLayout.CENTER);

        final TextAreaOutputStream textStream = new TextAreaOutputStream(textArea);

        JPanel bottom = new JPanel();
        bottom.setLayout(new BorderLayout());

        // a button.
        JButton clear = new JButton("Clear");
        clear.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.setText("");
                textStream.close();
            }
        });
        bottom.add(clear, BorderLayout.EAST);

        container.add(bottom, BorderLayout.SOUTH);
        add(container);

        // model processing.

        load.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(e);
                if (path.getText() != null && path.getText().length() > 0) {
                    try {
                        LogReader.execute(path.getText(), textStream);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                        JOptionPane.showMessageDialog(getParent(), e1.getMessage(), "ERROR", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
        });
    }

    private String lastVisited() {
        ObjectInputStream ois = null;
        try {
            ois = new ObjectInputStream(new FileInputStream("history.dat"));
            return (String) ois.readObject();
        } catch (Exception e) {
            return null;
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                }
            }
        }
    }

    private void saveVisited(String path) {
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream("history.dat"));
            oos.writeObject(path);
        } catch (Exception e) {
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static void main(String a[]) {
        View v = new View();
        v.init();
        v.setVisible(true);
    }
}
